﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;
using ChoViet.Model;
using ChoViet.Lib.Common;
using ChoViet.CMS.Properties;
using ChoViet.CMS.ViewModels;
using ChoViet.Lib.Paging;
using ChoViet.CMS.Components;
using ChoViet.CMS.Models;
namespace ChoViet.CMS.Controllers
{
    public class ApplicationsController : Controller
    {
        #region GET: /Applications

        #region Delete item in table
        [HttpPost]
        public JsonResult Del(int id, string type)
        {
            if (id == 0) return Json(false);
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                switch (type)
                {
                    case "AdAttributeValue": {
                        eDataContext.AdAttributeValues.DeleteOnSubmit(eDataContext.AdAttributeValues.FirstOrDefault(e => e.ID == id));
                        eDataContext.SubmitChanges(); eDataContext.Dispose();
                            break; }
                    case "Area":
                        {
                            eDataContext.Areas.DeleteOnSubmit(eDataContext.Areas.FirstOrDefault(e => e.ID == id));
                            eDataContext.SubmitChanges(); eDataContext.Dispose();
                            break;
                        }
                    case "Comment":
                        {
                            eDataContext.Comments.DeleteOnSubmit(eDataContext.Comments.FirstOrDefault(e => e.ID == id));
                            eDataContext.SubmitChanges(); eDataContext.Dispose();
                            break;
                        }
                    case "Tag":
                        {
                            //Delete All AdTagMap
                            var tagMaps = eDataContext.AdTagMaps.Where(e => e.TagID == id).ToList();
                            if (tagMaps != null && tagMaps.Count() > 0) eDataContext.AdTagMaps.DeleteAllOnSubmit(tagMaps);
                            eDataContext.SubmitChanges();
                            // Delete Tag;
                            eDataContext.Tags.DeleteOnSubmit(eDataContext.Tags.FirstOrDefault(e => e.ID == id));
                            eDataContext.SubmitChanges(); eDataContext.Dispose();
                            break;
                        }
                    case "Shop":
                        {
                            var currentShop = eDataContext.Shops.FirstOrDefault(e => e.ID == id);
                            //Delete All ShopAdMap
                            var shopAdMaps = eDataContext.ShopAdMaps.Where(e => e.ShopID == id).ToList();
                            if (shopAdMaps != null && shopAdMaps.Count() > 0) eDataContext.ShopAdMaps.DeleteAllOnSubmit(shopAdMaps);
                            eDataContext.SubmitChanges();
                            // Delete image
                            Uploads.DeleteFile(Settings.Default.AdminRootPath + currentShop.LogoPath.Replace('/', '\\'));    
                            // Delete Shop;

                            eDataContext.Shops.DeleteOnSubmit(currentShop);
                            eDataContext.SubmitChanges(); eDataContext.Dispose();
                            break;
                        }
                    case "Ad":
                        { 
                        // Delete Ad
                            var curentAd = eDataContext.Ads.FirstOrDefault(e => e.ID == id);
                            if (curentAd != null)
                            { 
                                // Delete avatar ad imge
                                if (!string.IsNullOrEmpty(curentAd.Image))
                                {
                                    var path = Settings.Default.AdminRootPath + curentAd.Image.Replace('/', '\\');
                                    Uploads.DeleteFile(path);
                                }
                                
                                // Delete description imge
                                var lst = eDataContext.Galleries.Where(e => e.AdID == id).ToList();
                                if (lst != null && lst.Count() > 0)
                                {
                                    foreach (var item in lst)
                                    {
                                        var itempath = Settings.Default.AdminRootPath + item.Path.Replace('/', '\\');
                                        Uploads.DeleteFile(itempath);
                                    }
                                    eDataContext.Galleries.DeleteAllOnSubmit(lst);
                                }
                                // Delete AdTagMap
                                var tagmaps = eDataContext.AdTagMaps.Where(e => e.AdID == id).ToList();
                                if (tagmaps != null && tagmaps.Count() > 0) {eDataContext.AdTagMaps.DeleteAllOnSubmit(tagmaps);}
                                // Delete all Comment
                                var comments = eDataContext.Comments.Where(e => e.AdID == id).ToList();
                                if (comments != null && comments.Count() > 0) { eDataContext.Comments.DeleteAllOnSubmit(comments); }
                                //Delete adAdtributema
                                var adadtributemap = eDataContext.AdAttributeMaps.Where(e => e.AdID == id).ToList();
                                if (adadtributemap != null && adadtributemap.Count() > 0)
                                {
                                    eDataContext.AdAttributeMaps.DeleteAllOnSubmit(adadtributemap);
                                }
                                // Delete FeedBack
                                var feedback = eDataContext.Feedbacks.Where(e => e.AdID == id).ToList();
                                if (feedback != null && feedback.Count() > 0) eDataContext.Feedbacks.DeleteAllOnSubmit(feedback);
                                eDataContext.SubmitChanges();
                                eDataContext.Ads.DeleteOnSubmit(curentAd);
                                eDataContext.SubmitChanges();
                            }
                            break;
                    }
                    default: return Json(false);
                }
               return Json(true);
            }
            catch (Exception ex) { return Json(ex.Message); }
        }
        #endregion

        #region LoadAreaByCountry
        public ActionResult LoadAreaByCountry(int id)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            LoadAreaByCountryVM model = new LoadAreaByCountryVM();
            if (id > 0) model.CountryID = id;
            else model.CountryID = 1;
            try
            {
                
                model.Areas = eDataContext.Areas.Where(e => id > 0 ? e.CountryID == id : e.CountryID == int.Parse(Settings.Default.ContryDefaultID.ToString())).ToList();
                return View(model);
            }
            catch(Exception ex)
            {
                return View(model);
            }
        }
        #endregion

        #region LoadCategoryByCountry
        public ActionResult LoadCategoryByCountry(int id)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            LoadCategoryByCountryVM model = new LoadCategoryByCountryVM();
            try
            {   
             //   model.Categories = eDataContext.Categories.Where(e => id > 0 ? e.CountryID == id : e.CountryID == int.Parse(Settings.Default.ContryDefaultID.ToString())).ToList();
                return View(model);
            }
            catch(Exception ex)
            {
                eDataContext.Dispose();
                return View(model);
            }
        }
        #endregion

        #region
        [HttpPost]
        public ActionResult LoadCityByCountry(int id)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            LoadCityByCountryVM model = new LoadCityByCountryVM();
            model.CountryID = id;
            try
            {
                model.Cities = eDataContext.Cities.Where(e => id > 0 ? e.CountryID == id : e.CountryID == int.Parse(Settings.Default.ContryDefaultID)).ToList();
                return View(model);
            }
            catch (Exception ex)
            {
                return View(model);
            }
        }
        #endregion

        #region LoadCityByArea
        [HttpPost]
        public ActionResult LoadCityByArea(int id)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            LoadCityByAreaVM model = new LoadCityByAreaVM();
            try
            {
                
                model.Cities = eDataContext.Cities.Where(d =>id>0 ? d.AreaID == id : true).ToList();
                if (id > 0) model.CountryID = eDataContext.Areas.Where(e => e.ID == id).Select(e => e.CountryID).FirstOrDefault().Value;
                else model.CountryID = 1;
                return View(model);
            }
            catch (Exception ex)
            {
                eDataContext.Dispose();
                return View(model);
            }
        }
        #endregion

        #region LoadDistrictByCity
        [HttpPost]
        public ActionResult LoadDistrictByCity(int id)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                var dic = eDataContext.Districts.Where(d => d.CityID == id).ToList();
                return View(dic);
            }
            catch (Exception ex)
            {
                eDataContext.Dispose();
                //Response.StatusCode = 404;
                //Response.Write(ex.Message);
                //throw ex;
                return View(new List<District>());
            }
        }
        #endregion

        #region SearchTag
        public JsonResult SearchTag()
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                eDataContext.DeferredLoadingEnabled = false;
                var term = Request["keyword"].ToString();
                var keywords = eDataContext.Tags
                    .Where(e => e.Name.IndexOf(term) > -1)
                    .Take(20)
                    .ToList();
                return Json(keywords, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json("", JsonRequestBehavior.AllowGet);
            }
        }
        #endregion

        #region SearchUser
        public JsonResult SearchUser()
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                eDataContext.DeferredLoadingEnabled = false;
                var term = Request["keyword"].ToString();
                var keywords = eDataContext.Users
                    .Where(e => e.UserName.IndexOf(term) > -1)
                    .Take(20)
                    .ToList();
                return Json(keywords, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json("", JsonRequestBehavior.AllowGet);
            }
        }
        #endregion


        #region SearchAd
        public JsonResult SearchAd()
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                eDataContext.DeferredLoadingEnabled = false;
                var term = Request["keyword"].ToString();
                var keywords = eDataContext.Ads
                    .Where(e => e.Title.IndexOf(term) > -1)
                    .Take(20)
                    .ToList();
                return Json(keywords, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json("", JsonRequestBehavior.AllowGet);
            }
        }
        #endregion

        #region ApplyChangYN for field of table  
        public void ApplyChangeYN(string tableName, string fieldName, int id, bool pubYN)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                if (tableName == "Ad")
                {
                    var item = eDataContext.Ads.Where(e => e.ID == id).FirstOrDefault();
                    if (fieldName == "PublishYN")
                    {
                        item.PublishYN= !pubYN;
                        if (item.ViewNumber == null || item.ViewNumber <= 0) item.ViewNumber = Utils.Random2Number(1,9);
                        eDataContext.SubmitChanges();
                    }
                    if (fieldName == "ActiveYN")
                    {
                        item.ActiveYN = !pubYN;
                        eDataContext.SubmitChanges();
                    }
                    if (fieldName == "Status")
                    {
                        if (pubYN) item.Status = 0;
                        else item.Status = 1;
                        eDataContext.SubmitChanges();
                    }
                    if (fieldName == "SetVIPStatus")
                    {
                        if (pubYN)
                            item.Status = item.Status - 2;
                        else
                        {
                            if (item.Status == null)
                            {
                                item.Status = 2;
                            }
                            else
                                item.Status = item.Status + 2;
                        }
                        eDataContext.SubmitChanges();
                    }
                }
                if (tableName == "Comment")
                {
                    var item = eDataContext.Comments.Where(e => e.ID == id).FirstOrDefault();
                    if (fieldName == "PublishYN")
                    {
                        item.PublishYN = !pubYN;
                        eDataContext.SubmitChanges();
                    }
                }
                if (tableName == "User")
                {
                    var item = eDataContext.Users.Where(e => e.ID == id).FirstOrDefault();
                    if (fieldName == "ActiveYN")
                    {
                        item.ActiveYN= !pubYN;
                        eDataContext.SubmitChanges();
                    }
                    if (fieldName == "OperationYN")
                    {
                        item.OperationYN = !pubYN;
                        eDataContext.SubmitChanges();
                    }
                }
                if (tableName == "Shop")
                {
                    var item = eDataContext.Shops.Where(e => e.ID == id).FirstOrDefault();
                    if (fieldName == "PubYN")
                    {
                        item.PubYN = !pubYN;
                        eDataContext.SubmitChanges();
                    }
                    if (fieldName == "FocusYN")
                    {
                        item.FocusYN = !pubYN;
                        eDataContext.SubmitChanges();
                    }
                }
                eDataContext.Dispose();
                return ;
            }
            catch (Exception exp)
            {
                Response.StatusCode = 404;
                Response.Write(exp.Message);
            }
        }
        #endregion

        #region AddComment
        public ContentResult AddComment(int id, int type)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            eDataContext.DeferredLoadingEnabled = false;
            Comment cmt = new Comment();
            var bs = new BaseAuthentication();
            cmt.AdID = id;
            if (type > 0)
            {
                cmt.ParentID = type;
            }
            //cmt.Name = Request["name"] != null ? Request["name"].ToString() : string.Empty;
            cmt.Email = Request["email"] != null ? Request["email"].ToString() : string.Empty;
            cmt.Title = Request["name"];

            
            var curentUser = bs.CurrentUser;
            if (curentUser != null && cmt.Email == curentUser.Email)
                cmt.UserID = curentUser.ID;
            cmt.CreatedDate = DateTime.Now;
            cmt.Content = Request["content"];
            eDataContext.Comments.InsertOnSubmit(cmt);
            eDataContext.SubmitChanges();
            return Content("true");
        }

        #endregion


        #region LoadShopByScrolling
        public ActionResult LoadShopByScrolling(int id)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            var param = new LoadShopByScrollingViewModel();
            try
            {
                param.Shops = eDataContext.Shops.Where(e => e.PubYN == true && e.LockYN == false).OrderBy("VIPID","ASC").ToPagedList(id, Convert.ToInt32(Settings.Default.ShopPageSize));
                return View(param);
            }
            catch { eDataContext.Dispose(); return View(param); }
        }

        #endregion

        public JsonResult CheckExistItem(string id)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            var itemName = Request["itemName"];
            if (id == "userName")
            {
                var exits = eDataContext.Users.Where(e => e.UserName == itemName).Count();
                if (exits > 0) return Json(false);
                else return Json(true);
            }
            else if (id == "email")
            {
                var exits = eDataContext.Users.Where(e => e.Email == itemName).Count();
                if (exits > 0) return Json(false);
                else return Json(true);
            }
            else return Json(false);
        }

        public ActionResult ChangeCurrentCountry(int id)
        {
            if (id > 0)
            {
                Session.Remove("CurCountryID");
                Session["CurCountryID"] = id.ToString();
            }
            return View();
        }
        public CaptchaImageResult ShowCaptchaImage()
        {
            return new CaptchaImageResult();
        }
        public JsonResult ValidateCatcha()
        {
            try
            {
                if (Request["CaptchaText"].ToLower() == HttpContext.Session["captchastring"].ToString().ToLower())
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(false, JsonRequestBehavior.AllowGet);
                }
            }
            catch
            {
                return Json(false, JsonRequestBehavior.AllowGet);
            }
        }

        #endregion
    }
}
